﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ControlCenter.Model;
using ControlCenter.Model.BizEntities;
using ControlCenter.Model.WebApiDto;
using Dapper;

namespace ControlCenter.Data
{
    /// <summary>
    /// 机器人仓储类
    /// </summary>
    public class RobotRepository : RepositoryBase, IRobotRepository
    {
        #region CRUD
        private const string QuerySql = @"
SELECT [RobotId]
      ,[Name]
      ,[Version]
      ,[Status]
  FROM [dbo].[RobotInfo]";

        private const string UpdateOrSaveSql = @"
IF EXISTS ( SELECT * FROM RobotInfo rp WHERE rp.RobotId=@RobotId ) UPDATE RobotInfo 
SET [Name] =@Name,
[Version] =@Version,
[Status] =@Status,
[Ip] =@Ip
WHERE
	RobotId =@RobotId ELSE INSERT INTO RobotInfo ( [RobotId], [Name], [Version], [Status], [Ip] )
VALUES (@RobotId,@Name,@Version,@Status,@Ip)";

        private const string QueryRobotInfoDtoSql = @"
SELECT R.RobotId,R.Name RobotName,R.Version RobotVersion,R.Status RobotStatus,R.Ip,
	P.PackageId,P.ProjectName PackageName,P.Version PackageVersion,
	Rp.PackageStatus,Rp.IsInstall,Rp.ExecCycleName,Rp.RpId 
FROM dbo.RobotInfo AS R
LEFT JOIN (SELECT TOP 1 * FROM dbo.RobotPackage WHERE PackageStatus=4) AS Rp ON Rp.RobotId=R.RobotId
LEFT JOIN dbo.ProjectPackageInfo AS P ON Rp.PackageId=P.PackageId
WHERE 1=1 {0} 
ORDER BY RobotName ASC,PackageName ASC";
        #endregion

        /// <summary>
        /// 根据条件查询机器人数据
        /// </summary>
        /// <param name="paramDto"></param>
        /// <returns></returns>
        public async Task<IEnumerable<RobotInfoDto>> Query(RobotQueryDto paramDto)
        {
            string sql = QueryRobotInfoDtoSql;
            string sqlWhere = string.Empty;
            if (!string.IsNullOrEmpty(paramDto.Keywords))
            {
                paramDto.Keywords = "%" + paramDto.Keywords + "%";
                sqlWhere = $" and R.Name like @Keywords ";
            }

            sql = string.Format(sql, sqlWhere);
            return await ControlCenterDbConn.QueryAsync<RobotInfoDto>(sql, new { Keywords = paramDto.Keywords });
        }

        /// <summary>
        /// 通过ID查找机器人
        /// </summary>
        /// <param name="robotId"></param>
        /// <returns></returns>
        public async Task<RobotInfo> Find(Guid robotId)
        {
            string sql = @"SELECT * FROM RobotInfo WHERE RobotId=@RobotId";
            return await ControlCenterDbConn.QueryFirstOrDefaultAsync<RobotInfo>(sql, new {RobotId = robotId});
        }

        /// <summary>
        /// 更新机器人状态
        /// </summary>
        /// <param name="robotId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<bool> UpdateRobotStatus(Guid robotId, int status)
        {
            string sql = @"UPDATE RobotInfo SET Status=@Status WHERE RobotId=@RobotId";
            return await ControlCenterDbConn.ExecuteAsync(sql, new {RobotId=robotId, Status=status}) > 0;
        }

        /// <summary>
        /// 新增或更新机器人信息
        /// </summary>
        /// <param name="robotInfo"></param>
        /// <returns></returns>
        public async Task<bool> UpdateOrSave(RobotInfo robotInfo)
        {
            return await ControlCenterDbConn.ExecuteAsync(UpdateOrSaveSql, robotInfo) > 0;
        }

        /// <summary>
        /// 删除机器人
        /// </summary>
        /// <param name="robotId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteRobot(Guid robotId)
        {
            string sql = @"DELETE RobotInfo WHERE RobotId=@RobotId;DELETE RobotPackage WHERE RobotId=@RobotId";
            return await ControlCenterDbConn.ExecuteAsync(sql, new {RobotId = robotId}) > 0;
        }
    }
}
